package com.zhongxi.guoyuan.fragment.beanexchange;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.personExchangeOrder.PersonExchangeNoPayAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseFragment;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.clearweed.PersonExchangeResult;
import com.zhongxi.guoyuan.entity.coinStore.ItemGoodAttr;
import com.zhongxi.guoyuan.entity.coinStore.NoPayAddress;
import com.zhongxi.guoyuan.entity.coinStore.PostcartAttrsCollection;
import com.zhongxi.guoyuan.entity.coinStore.SelcetPostCartGoodsAttrs;
import com.zhongxi.guoyuan.entity.coinStore.ShopInfos;
import com.zhongxi.guoyuan.entity.rewardcoin.MirrorInfo;
import com.zhongxi.guoyuan.entity.rewardcoin.RewardCoinOrderInfo;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.view.beanExchange.PersonExchangeActivity;
import com.zhongxi.guoyuan.view.beanExchange.PersonExchangePayActivity;
import com.zhongxi.guoyuan.view.personalCenter.ExchangePayActivity;
import com.zhongxi.guoyuan.view.rewardCoin.ApplyRewardActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public class ExchangeNoPayFragment extends BaseFragment implements PullToRefreshBase.OnRefreshListener2<ListView> {


    @Bind(R.id.pullToRefreshListView)
    PullToRefreshListView mPullToRefreshListView;


    private PersonExchangeNoPayAdapter mNoPayAdapter;


    private List<PersonExchangeResult.OrderInfo> mInfoList = new ArrayList<>();
    private String orderCus;
    private String shopInfo;
    private String goodsInfo;
    private PersonExchangeResult personExchangeResult;
    private String type;
    private int position;
    private JSONObject jsonshopInfo;
    private JSONObject jsonOrderCus;
    private JSONObject jsonGoodsInfo;
    private JSONObject info;

    public ExchangeNoPayFragment() {
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            position=msg.getData().getInt("pos");

            switch (msg.what){
                case 1://delete
                  deteleItem();
                    break;
                case 2:

                    break;
            }
        }
    };



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mView = inflater.inflate(R.layout.fragment_exchange_no_pay, container, false);
        ButterKnife.bind(this, mView);
        return mView;
    }

    @Override
    protected void initView() {
        super.initView();
        mPullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        mPullToRefreshListView.setOnRefreshListener(this);

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden)
            getData();
    }

    @Override
    protected void initData() {
        super.initData();
        mNoPayAdapter = new PersonExchangeNoPayAdapter(mHandler, getContext());
        mPullToRefreshListView.setAdapter(mNoPayAdapter);
        getData();
    }

    public void getData() {
        type = "order";
        String str = "&page=" + pageNum;
        getServer(Url.EXCHANGE_NOPAY, null, str, false, null, "get");
    }



    private void deteleItem() {
        type="delete";
        Map<String,String> map=new HashMap<>();
        map.put("ordertype",mInfoList.get(position).getOrdertype());
        map.put("orderid",mInfoList.get(position).getId());

        for (String key:map.keySet()) {
            Log.d("flag", "nopaydeteleItem: "+key+" : "+map.get(key));
        }
        getServer(Url.EXCHANGE_DELETENOPAY, map, "", false, null, "post");
    }



    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson mGson = new Gson();
        if (type.equals("order")){
            personExchangeResult = mGson.fromJson(response, PersonExchangeResult.class);
            MyApplication.getInstance().setSpValue(personExchangeResult.getSafeobj());
            if (personExchangeResult.getCode() == 1) {
                if (mPullToRefreshListView.isRefreshing())
                    mPullToRefreshListView.onRefreshComplete();

                if (pageNum == 1) {
                    mInfoList.clear();
                }

                if (personExchangeResult.getOrderInfo().size()>0){
                    mInfoList.addAll(personExchangeResult.getOrderInfo());
                }else {
                    if (pageNum!=1)
                        pageNum--;
                }

                try {
                    JSONObject mJSONObject=new JSONObject(response);
                    if (mJSONObject.optString("orderCus") != null) {
                        orderCus=mJSONObject.optString("orderCus");
                        jsonOrderCus=new JSONObject(orderCus);

                    }
                    if (mJSONObject.optString("shopInfo") != null) {
                        shopInfo=mJSONObject.optString("shopInfo");
                        jsonshopInfo=new JSONObject(shopInfo);
                    }
                    if (mJSONObject.optString("goodsInfo") != null) {
                        goodsInfo=mJSONObject.optString("goodsInfo");
                        jsonGoodsInfo=new JSONObject(goodsInfo);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                mNoPayAdapter.setData(mInfoList, orderCus, shopInfo,goodsInfo, (PersonExchangeActivity) getActivity());
                mNoPayAdapter.notifyDataSetChanged();
            }
        }else if (type.equals("delete")){
            BaseResponse mResponse=mGson.fromJson(response,BaseResponse.class);
            MyApplication.getInstance().setSpValue(mResponse.getSafeobj());
            mInfoList.remove(position);
            mNoPayAdapter.notifyDataSetChanged();
            getData();
        }

    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson=new Gson();
        BaseResponse mBaseResponse=gson.fromJson(response,BaseResponse.class);
        if(null!=mBaseResponse.getSafeobj()&&!"".equals(mBaseResponse.getSafeobj())){
            MyApplication.getInstance().setSpValue(mBaseResponse.getSafeobj());
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum = 1;
        getData();

    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum++;
        getData();
    }
}
